package org.dtrd.modules.record.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.common.util.DateUtils;
import org.dtrd.config.system.Constant;
import org.dtrd.config.system.Constant.RecordType;
import org.dtrd.modules.achievement.service.IDtrdEntRdSigninRecordService;
import org.dtrd.modules.record.entity.bean.AvgRecordBean;
import org.dtrd.modules.record.entity.bean.DailyKetoneRecordBean;
import org.dtrd.modules.record.entity.bean.KetoneStatisticBean;
import org.dtrd.modules.record.entity.bean.CheckinRecord;
import org.dtrd.modules.record.entity.po.DtrdEntRdSigninKetone;
import org.dtrd.modules.record.mapper.DtrdEntRdKetoneMapper;
import org.dtrd.modules.record.service.IKetoneRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 萧
 * @date:2021-08-22
 **/
@Slf4j
@Service
@DS("multi-datasource1")
public class KetoneRecordServiceImpl extends ServiceImpl<DtrdEntRdKetoneMapper, DtrdEntRdSigninKetone> implements IKetoneRecordService {

    @Autowired
    private IDtrdEntRdSigninRecordService signinRecordService;

    @Override
    public DtrdEntRdSigninKetone transformRecord(CheckinRecord checkinRecord) {
        DtrdEntRdSigninKetone dt = new DtrdEntRdSigninKetone().init();
        dt.setKetoneRemark(checkinRecord.getRemark());
        dt.setKetoneValue(checkinRecord.getKetone());
        dt.setKetoneDescribe(checkinRecord.getKetoneDesc());
        dt.setPatientId(checkinRecord.getPatientId());
        dt.setRecordTime(parseStringAsDateTime(checkinRecord.getRecordTime()));
        dt.setRecordDate(parseStringAsDate(checkinRecord.getRecordTime()));
        dt.setRecordPhoto(checkinRecord.getImages());
        return dt;
    }

    @Override
    public CheckinRecord transformPO(DtrdEntRdSigninKetone po) {
        if (po == null) {
            return null;
        }
        CheckinRecord checkinRecord = new CheckinRecord();
        checkinRecord.setRecordTime(DateUtils.formatTime(po.getRecordTime()));
        checkinRecord.setRecordTimeHm(DateUtils.formatShortTime(po.getRecordTime()));
        checkinRecord.setDataId(po.getDataId());
        checkinRecord.setImages(po.getRecordPhoto());
        checkinRecord.setPatientId(po.getPatientId());
        checkinRecord.setRecordType(Constant.RecordType.KETONE.getType());
        checkinRecord.setRecordTypeName(Constant.RecordType.KETONE.getName());
        checkinRecord.setRemark(po.getKetoneRemark());
        checkinRecord.setKetoneDesc(po.getKetoneDescribe());
        checkinRecord.setKetone(po.getKetoneValue());
        return checkinRecord;
    }

    @Override
    public LambdaQueryWrapper<DtrdEntRdSigninKetone> generateSelectRecordByDateQuery(Integer patientId, String date, Integer subType) {
        LambdaQueryWrapper<DtrdEntRdSigninKetone> query = new LambdaQueryWrapper<>();
        query.eq(DtrdEntRdSigninKetone::getIsDel, 0)
                .eq(DtrdEntRdSigninKetone::getPatientId, patientId)
                .eq(DtrdEntRdSigninKetone::getRecordDate, date);
        return query;
    }

    @Override
    public Integer getKetoneRecordCount(Integer patientId, String startDate, String endDate) {
        return baseMapper.countKetoneRecord(patientId, startDate, endDate);
    }

    @Override
    public List<DailyKetoneRecordBean> getAllGroupedKetoneRecord(Integer patientId, String startDate, String endDate, Integer page, Integer pageSize) {
        int pageStart = (page - 1) * pageSize;
        List<DtrdEntRdSigninKetone> list = baseMapper.getAllGroupedKetoneRecord(patientId, startDate, endDate, pageStart, pageSize);
        if (list != null) {
            ArrayList<DailyKetoneRecordBean> resultList = new ArrayList<>(list.size());
            list.stream().map(po -> new DailyKetoneRecordBean().parseFromPo(po)).forEach(resultList::add);
            return resultList;
        }
        return Collections.EMPTY_LIST;
    }

    @Override
    public KetoneStatisticBean getKetoneRecordStatistic(Integer patientId, String startDate, String endDate) {
        KetoneStatisticBean ketoneStatisticBean = new KetoneStatisticBean();
        Integer totalCount = baseMapper.countKetoneRecord(patientId, startDate, endDate);
        // 没记录就直接返回
        if (totalCount == 0) {
            ketoneStatisticBean.setKetoneCount(0);
            return ketoneStatisticBean;
        } else {
            ketoneStatisticBean.setKetoneCount(totalCount);
        }
        Integer negative = baseMapper.countKetoneNegative(patientId, startDate, endDate);
        ketoneStatisticBean.setKetoneNegativeCount(negative);
        Integer weaklyPositive = baseMapper.countKetoneWeaklyPositive(patientId, startDate, endDate);
        ketoneStatisticBean.setKetoneWeaklyPositiveCount(weaklyPositive);
        Integer positive = baseMapper.countKetonePositive(patientId, startDate, endDate);
        ketoneStatisticBean.setKetonePositiveCount(positive);
        Integer stronglyPositive = baseMapper.countKetoneStronglyPositive(patientId, startDate, endDate);
        ketoneStatisticBean.setKetoneStronglyPositiveCount(stronglyPositive);
        return ketoneStatisticBean;
    }

    @Override
    public AvgRecordBean getAvgValue(Integer patientId, String startDate, String endDate) {
        return baseMapper.getAvgValue(patientId, startDate, endDate);
    }

    @Override
    public Boolean saveOrUpdateKetone(DailyKetoneRecordBean ketoneInfo) {
        Integer patientId = ketoneInfo.getPatientId();
        DtrdEntRdSigninKetone po = new DtrdEntRdSigninKetone();
        if (ketoneInfo.getDataId() == null) {
            po = new DtrdEntRdSigninKetone().init();
        }
        po = po.parseFromDTO(ketoneInfo);
        LambdaUpdateWrapper<DtrdEntRdSigninKetone> wrapper = Wrappers.lambdaUpdate(DtrdEntRdSigninKetone.class)
                .eq(DtrdEntRdSigninKetone::getPatientId, patientId)
                .eq(DtrdEntRdSigninKetone::getRecordDate, po.getRecordDate());
        boolean result = saveOrUpdate(po, wrapper);
        // 补充打卡
        log.info("KetoneRecordServiceImpl.saveOrUpdateKetone.[ketoneInfo] patientId=" + patientId + "; result=" + result + "; dataId=" + po.getDataId());
        if (po.getDataId() == null) {
            po = getOne(wrapper);
        }
        signinRecordService.saveSigninRecord(po.getDataId(), 0, mapper ->
                mapper.apply(ketoneInfo.getPatientId())
                        .withRecordType(RecordType.KETONE.getType())
                        .withRecordTime(ketoneInfo.getRecordTime())
                        .withRecordDesc(ketoneInfo.getKetoneDescribe())
                        .withRecordValue(ketoneInfo.getKetoneValue() + "")
                        .withRemark(ketoneInfo.getKetoneRemark())
                        .withImages(ketoneInfo.getKetoneRecordPhoto())
                        .build()
        );
//        Date recordDate = po.getRecordDate();
//        DtrdEntRdSigninKetone po = getOne(wrapper);
//        signinRecordService.saveSigninRecord(po.getDataId(), patientId,
//                Constant.RecordType.KETONE.getType(), 0,
//                DateUtils.formatDate(recordDate, DateUtils.date_sdf.get().toPattern()));
        return result;
    }
}
